"""
项目管理专业代理角色
实现各个专业角色的代理函数
"""

from typing import Dict, Any
from src.research_core.project_state import ProjectManagementState
from src.research_core.project_prompts import (
    PROJECT_COORDINATOR_PROMPT, PRODUCT_MANAGER_PROMPT,
    UI_UX_DESIGNER_PROMPT, DEVELOPER_PROMPT, TESTER_PROMPT,
    COLLABORATION_PROMPT, FEEDBACK_PROMPT, PHASE_TRANSITION_PROMPT,
    PROMPT_ANALYSIS_PROMPT, PROMPT_OPTIMIZATION_PROMPT, PROMPT_EVALUATION_PROMPT
)

# 使用依赖注入减少循环导入
llm = None

def _initialize_components():
    """延迟初始化组件"""
    global llm
    if llm is None:
        from src.research_core.model import get_llm
        llm = get_llm()

def _invoke_llm_safely(messages: list) -> str:
    """安全地调用LLM并处理异常"""
    try:
        if llm is None:
            raise Exception("LLM未初始化")
        response = llm.invoke(messages)
        if hasattr(response, 'content'):
            return response.content if isinstance(response.content, str) else str(response.content)
        else:
            return str(response)
    except Exception as e:
        return f"调用失败: {str(e)}"

def project_coordinator_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """项目协调员代理：项目管理协调"""
    _initialize_components()
    
    # 构建团队信息字符串
    team_info = ""
    for role, members in state.get("team_members", {}).items():
        team_info += f"{role}: {', '.join(members)}\n"
    
    messages = PROJECT_COORDINATOR_PROMPT.format_messages(
        project_name=state.get("project_name", "未命名项目"),
        project_description=state.get("project_description", ""),
        current_phase=state.get("project_phase", "requirements"),
        team_members=team_info or "暂无团队成员",
        current_state=str(state.get("requirements_analysis", {}))
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "coordination_plan": response_content,
        "next_actions": "协调团队工作，推进项目进展"
    }

def product_manager_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """产品经理代理：需求分析和产品设计"""
    _initialize_components()
    
    # 构建团队信息字符串
    team_info = ""
    for role, members in state.get("team_members", {}).items():
        team_info += f"{role}: {', '.join(members)}\n"
    
    messages = PRODUCT_MANAGER_PROMPT.format_messages(
        project_name=state.get("project_name", "未命名项目"),
        project_description=state.get("project_description", ""),
        user_requirements=state.get("question", "暂无明确需求"),
        market_analysis="基于项目目标进行市场分析",
        team_members=team_info or "暂无团队成员",
        feedback_history=str(state.get("feedback_history", [])[-3:])  # 最近3条反馈
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "requirements_analysis": {
            "functional_requirements": "从产品设计中提取的功能需求",
            "non_functional_requirements": "性能、安全、可用性等需求",
            "priority_list": ["高优先级功能1", "中优先级功能2", "低优先级功能3"]
        },
        "product_design": response_content
    }

def ui_ux_designer_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """UI/UX设计师代理：界面设计"""
    _initialize_components()
    
    product_design = state.get("product_design", {})
    if isinstance(product_design, dict):
        product_requirements = str(product_design)
    else:
        product_requirements = product_design
    
    messages = UI_UX_DESIGNER_PROMPT.format_messages(
        product_requirements=product_requirements,
        target_users="项目目标用户群体",
        design_constraints="技术实现限制和设计规范"
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "ui_ux_design": {
            "wireframes": "界面线框图描述",
            "interaction_flow": "用户交互流程",
            "visual_design": response_content,
            "design_system": "设计规范和组件库"
        }
    }

def developer_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """开发工程师代理：技术实现"""
    _initialize_components()
    
    product_design = state.get("product_design", {})
    ui_ux_design = state.get("ui_ux_design", {})
    
    messages = DEVELOPER_PROMPT.format_messages(
        product_design=str(product_design),
        ui_ux_design=str(ui_ux_design),
        technical_requirements="技术实现要求和约束"
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "development_code": response_content,
        "technical_architecture": {
            "backend": "后端技术架构",
            "frontend": "前端技术架构",
            "database": "数据库设计",
            "api_design": "API接口设计"
        }
    }

def tester_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """测试工程师代理：质量保证"""
    _initialize_components()
    
    development_code = state.get("development_code", "")
    requirements = state.get("requirements_analysis", {})
    
    messages = TESTER_PROMPT.format_messages(
        development_code=development_code[:1000] if development_code else "无代码内容",
        functional_requirements=str(requirements.get("functional_requirements", [])),
        quality_goals="高质量、高可靠性、良好性能"
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "test_cases": [
            {
                "id": "TC001",
                "description": "主要功能测试用例",
                "steps": "测试步骤描述",
                "expected_result": "预期结果"
            }
        ],
        "test_results": {
            "pass_rate": 0.85,
            "defects_found": 5,
            "test_coverage": 0.9,
            "quality_assessment": response_content
        }
    }

def collaboration_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """协作代理：实时协作管理"""
    _initialize_components()
    
    team_info = ""
    for role, members in state.get("team_members", {}).items():
        team_info += f"{role}: {', '.join(members)}\n"
    
    messages = COLLABORATION_PROMPT.format_messages(
        collaboration_context=f"项目{state.get('project_name', '未命名项目')}的实时协作",
        team_members=team_info,
        current_issues="协作效率和沟通问题"
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "collaboration_plan": response_content,
        "communication_channels": ["实时聊天", "文档协同", "视频会议"],
        "feedback_mechanism": "定期反馈和评审流程"
    }

def feedback_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """反馈代理：反馈处理"""
    _initialize_components()
    
    feedback_history = state.get("feedback_history", [])
    recent_feedback = feedback_history[-3:] if feedback_history else []
    
    messages = FEEDBACK_PROMPT.format_messages(
        project_phase=state.get("project_phase", "requirements"),
        feedback_content=str(recent_feedback),
        feedback_source="团队成员反馈"
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "feedback_analysis": response_content,
        "improvement_actions": [
            "优化工作流程",
            "改进沟通机制",
            "加强质量控制"
        ]
    }

def phase_transition_agent(state: ProjectManagementState) -> Dict[str, Any]:
    """阶段转换代理：项目阶段管理"""
    _initialize_components()
    
    current_phase = state.get("project_phase", "requirements")
    next_phase = _get_next_phase(current_phase)
    phase_results = _get_phase_results(state, current_phase)
    
    messages = PHASE_TRANSITION_PROMPT.format_messages(
        current_phase=current_phase,
        phase_results=str(phase_results),
        next_phase=next_phase
    )
    
    response_content = _invoke_llm_safely(messages)
    
    return {
        "transition_plan": response_content,
        "next_phase": next_phase,
        "completion_criteria": "阶段完成标准清单"
    }

def _get_next_phase(current_phase: str) -> str:
    """获取下一个项目阶段"""
    phases = ["requirements", "design", "development", "testing", "deployment"]
    try:
        current_index = phases.index(current_phase)
        if current_index < len(phases) - 1:
            return phases[current_index + 1]
        return "completed"
    except ValueError:
        return "requirements"

def _get_phase_results(state: ProjectManagementState, phase: str) -> Dict[str, Any]:
    """获取阶段成果"""
    if phase == "requirements":
        return state.get("requirements_analysis", {})
    elif phase == "design":
        return {
            "product_design": state.get("product_design", {}),
            "ui_ux_design": state.get("ui_ux_design", {})
        }
    elif phase == "development":
        return {
            "development_code": state.get("development_code", "")[:500] + "..." if state.get("development_code") else "",
            "technical_architecture": state.get("technical_architecture", {})
        }
    elif phase == "testing":
        return {
            "test_cases": state.get("test_cases", []),
            "test_results": state.get("test_results", {})
        }
    return {}

def analyze_prompt_requirement(state: ProjectManagementState) -> Dict[str, Any]:
    """
    分析提示词需求
    """
    _initialize_components()
    
    messages = PROMPT_ANALYSIS_PROMPT.format_messages(
        prompt_requirement=state['question']
    )
    
    analysis = _invoke_llm_safely(messages)
    
    return {
        "requirement_analysis": analysis,
        "current_prompt": None,
        "final_prompt": None
    }

def design_initial_prompt(state: ProjectManagementState) -> Dict[str, Any]:
    """
    设计初始提示词
    """
    _initialize_components()
    
    # 这里我们可以从分析结果中提取关键信息来构建提示词
    # 为了简化，我们创建一个基于分析的提示词设计
    analysis = state.get('requirement_analysis', '')
    
    # 构造一个初始提示词设计
    initial_prompt_design = f"""根据以下需求分析设计提示词：

{analysis}

请提供一个结构清晰、目标明确的提示词模板。"""
    
    messages = [("human", initial_prompt_design)]
    
    prompt_design = _invoke_llm_safely(messages)
    
    return {
        "current_prompt": prompt_design
    }

def evaluate_prompt(state: ProjectManagementState) -> Dict[str, Any]:
    """
    评估提示词质量
    """
    _initialize_components()
    
    current_prompt = state.get('current_prompt', '')
    
    messages = PROMPT_EVALUATION_PROMPT.format_messages(
        prompt_to_evaluate=current_prompt
    )
    
    evaluation = _invoke_llm_safely(messages)
    
    return {
        "prompt_evaluation": evaluation
    }

def optimize_prompt(state: ProjectManagementState) -> Dict[str, Any]:
    """
    优化提示词
    """
    _initialize_components()
    
    current_prompt = state.get('current_prompt', '')
    feedback = state.get('prompt_evaluation', '')
    optimization_goal = state.get('optimization_goal', '提高提示词的清晰度和有效性')
    
    messages = PROMPT_OPTIMIZATION_PROMPT.format_messages(
        current_prompt=current_prompt,
        feedback=feedback,
        optimization_goal=optimization_goal
    )
    
    optimized_prompt = _invoke_llm_safely(messages)
    
    return {
        "current_prompt": optimized_prompt
    }

def finalize_prompt(state: ProjectManagementState) -> Dict[str, Any]:
    """
    最终确定提示词
    """
    current_prompt = state.get('current_prompt', '')
    
    # 提取最终提示词（这里可以进一步处理）
    final_prompt = current_prompt
    design_reasoning = "基于需求分析和多轮优化生成的提示词"
    
    return {
        "final_prompt": final_prompt,
        "design_reasoning": design_reasoning,
        "workflow_complete": True
    }